import { getUserInfoAPI, loginApi, updatePassword } from '@/api/user'
import router, { constantRoutes } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'
const state = {
  // 防止刷新丢失token
  token: getToken(),
  userInfo: {},
  routes: constantRoutes
}

const mutations = {
  // 只能用mutations修改state中的数据
  saveToken(state, payload) {
    state.token = payload
  },

  saveUserInfo(state, payload) {
    state.userInfo = payload
  },

  setRoutes(state, payload) {
    // 新旧路由合并
    state.routes = [...constantRoutes, ...payload]
    router.addRoutes([...payload, { path: '*', redirect: '/404', hidden: true }])

  }
}

// 处理异步操作
const actions = {
  async loginActions(store, payload) {
    const res = await loginApi(payload)
    // 将token保存到vuex和本地存储中，提交修改数据到mutations
    store.commit('saveToken', res)
    setToken(res)
    router.push('/')
    Message({
      message: '登录成功',
      type: 'success'
    })
  },
  async updatePasswordActions(store, payload) {
    await updatePassword(payload)
    Message({
      message: '修改成功',
      type: 'success'
    })
  },

  async getUserInfoActions(store) {
    const res = await getUserInfoAPI()
    store.commit('saveUserInfo', res)
  },

  logoutAction(store) {
    store.commit('saveToken', '')
    store.commit('saveUserInfo', {})
    removeToken()
    router.push('/login')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

